//
//  UIView+Extension.swift
//  VISUAL
//
//  Created by 刘森 on 2019/11/28.
//  Copyright © 2019 admin. All rights reserved.
//

import UIKit

extension UIView {
    
    
    
    convenience init(backgroundColor: UIColor) {
        self.init()
        self.backgroundColor = backgroundColor
    }
    
    func addSubviews(_ subviews: [UIView]) {
        guard !subviews.isEmpty else {
            return
        }
        subviews.forEach {
            self.addSubview($0)
        }
    }
    func removeAllSubviews()  {
        self.subviews.forEach{
            $0.removeFromSuperview()
        }
    }
 
    func makeImageWithView() -> UIImage?  {
        guard self.bounds.size != CGSize.zero else {
            return nil
        }
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, true, UIScreen.main.scale)
        self.layer.render(in: UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}




private var LW_redDotCountLabelKey = 105

extension UIView {
    
    
    var lw_redDotCountLabel: UILabel? {
        set {
            objc_setAssociatedObject(self, &LW_redDotCountLabelKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        get {
            return objc_getAssociatedObject(self, &LW_redDotCountLabelKey) as? UILabel
        }
    }
    
    func lw_clearRedDot() {
        lw_showRedDot(0)
    }
    
    func lw_showRedDot(_ string: Int) {
        if string < 1 {
            lw_redDotCountLabel?.isHidden = true
            return
        }
        if string > 99 {
            getCountLabelText(string: "...")
            return
        }
        let str = String(format: "%ld", string)
        getCountLabelText(string: str)
    }
    
    
    private func getCountLabelText(string: String) {
        if lw_redDotCountLabel == nil {
            lw_redDotCountLabel = RedDotCountLabelStyle()
            self.addSubview(lw_redDotCountLabel!)
            lw_redDotCountLabel?.snp.makeConstraints({ (make) in
                make.width.height.equalTo(RedDotCountLabelWidth)
                make.centerX.equalTo(self.snp.right)
                make.centerY.equalTo(self.snp.top)
            })
        }
        lw_redDotCountLabel?.isHidden = false
        lw_redDotCountLabel?.text = string
    }
    
    
}

private var RedDotCountLabelWidth: CGFloat = 20
private var RedDotCountLabelStyle = { () -> UILabel in
    let value = UILabel()
    value.textAlignment = .center
    value.layer.cornerRadius = RedDotCountLabelWidth / 2
    value.backgroundColor = UIColor.red
    value.layer.masksToBounds = true
    value.textColor = UIColor.white
    value.font = KFont(13)
    return value
}

